/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.OrderCloseType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.enums.ShopWalletChangeReason;
import com.yami.shop.bean.event.ReceiptOrderEvent;
import com.yami.shop.bean.model.ShopWallet;
import com.yami.shop.bean.order.ConfirmOrderOrder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.ShopWalletMapper;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.ShopWalletLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;


/**
 * 确认收货的事件
 */
@Slf4j
@Component("defaultReceiptOrderListener")
@AllArgsConstructor
public class ReceiptOrderListener {

    private final ShopWalletMapper shopWalletMapper;

    private final ShopWalletLogService shopWalletLogService;

    private final MapperFacade mapperFacade;

    private final OrderRefundService orderRefundService;

    private final OrderService orderService;

    @EventListener(ReceiptOrderEvent.class)
    @Order(ConfirmOrderOrder.DISTRIBUTION)
    public void defaultReceiptOrderEvent(ReceiptOrderEvent event) {
        com.yami.shop.bean.model.Order order = event.getOrder();
        //如果是积分订单无需操作
        if(Objects.equals(order.getOrderType() , OrderType.SCORE.value())){
            return;
        }
        Long shopId = order.getShopId();
        ShopWallet shopWallet = shopWalletMapper.selectOne(new LambdaQueryWrapper<ShopWallet>().eq(ShopWallet::getShopId, shopId));
        ShopWallet newShopWallet = mapperFacade.map(shopWallet, ShopWallet.class);
        newShopWallet.setUpdateTime(new Date());

        // 退款成功金额
        double refundSuccessAmount = orderRefundService.sumRefundSuccessAmountByOrderId(order.getOrderId());

        // 分销占用金额
        double distributionAmount = orderService.sumTotalDistributionAmountByOrderItem(order.getOrderItems());
        // 平台占用金额
        double platformAmount = orderRefundService.sumRefundSuccessPlatformAmountByOrderId(order.getOrderId());


        // 结算金额 = (用户支付金额 + 平台补贴金额) - 退款成功金额 - 分销占用金额
        double shopAmount = Arith.add(order.getActualTotal(), order.getPlatformAmount());
        double settledAmount = Arith.sub(Arith.sub(Arith.sub(shopAmount, refundSuccessAmount), distributionAmount),platformAmount);

        // 不需要结算
        if (settledAmount < 0.01) {
            log.info("order not need settment, settledAmount < 0.01");
            return;
        }

        // 减去未结算金额
        newShopWallet.setUnsettledAmount(Arith.sub(shopWallet.getUnsettledAmount(),settledAmount));
        // 增加结算金额
        newShopWallet.setSettledAmount(Arith.add(shopWallet.getSettledAmount(),settledAmount));
        // 增加总结算金额
        newShopWallet.setTotalSettledAmount(Arith.add(shopWallet.getTotalSettledAmount(),settledAmount));
        // 插入收入记录
        if (Objects.equals(order.getStatus(), OrderStatus.CLOSE.value()) && Objects.equals(order.getCloseType(), OrderCloseType.REFUND.value())) {
            shopWalletLogService.saveShopWalletLog(shopWallet,newShopWallet, ShopWalletChangeReason.ORDER_REFUND,order.getOrderNumber());
        } else {
            shopWalletLogService.saveShopWalletLog(shopWallet,newShopWallet, ShopWalletChangeReason.ORDER_SUCCESS,order.getOrderNumber());
        }
        // 使用乐观锁进行更新
        if (shopWalletMapper.updateById(newShopWallet)!=1) {
            log.error("更新店铺钱包失败，无法确认收货，稍后再试");
            // 不要让用户看到更新店铺钱包失败的信息
            // 网络繁忙，请稍后重试
            throw new YamiShopBindException("yami.network.busy");
        }

    }

}
